import { OnChanges } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SFComponent, SFSchema, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { ContractManagementService } from '../../services/contract-management.service';

@Component({
  selector: 'app-contract-management-template-text-complaint',
  templateUrl: './contract-template-detail.component.html',
  styleUrls: ['./contract-template-detail.component.less'],
  providers: [DatePipe]
})
export class ContractManagementTemplateTextComponent implements OnInit {
  constructor(
    private nzModalService: NzModalService,
    public service: ContractManagementService,
    public route: ActivatedRoute,
    private datePipe: DatePipe,
    private router: Router,
    public shipperservice: ShipperBaseService
  ) {}
  textStatus = '新建模板';
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  schema: SFSchema = {};
  @ViewChild('sf2', { static: false }) sf2!: SFComponent;
  schema2: SFSchema = {};
  @ViewChild('sf3', { static: false }) sf3!: SFComponent;
  schema3: SFSchema = {};
  ui!: SFUISchema;
  ui2!: SFUISchema;
  ui3!: SFUISchema;
  sfdata: any;
  sfdata2: any;
  sfdata3: any;
  title: any;
  Types: any;
  templateHTML: any;
  detailList: any = {
    templateName: ''
  };
  isUpdate = false;
  ngOnInit() {
    this.initSF();
    this.initSF2();
    this.initSF3();
    if (this.route.snapshot.queryParams.status == 1) {
      // 新建
      this.isUpdate = true;
    } else if (this.route.snapshot.queryParams.status == 2) {
      // 编辑
      this.textStatus = '编辑模板';
      this.isUpdate = true;
      this.initData(this.service.$api_get_contractTemplate);
    } else if (this.route.snapshot.queryParams.status == 3) {
      // 编辑
      this.textStatus = '查看模板';
      this.isUpdate = false;
      this.initData(this.service.$api_get_contractTemplate);
    }
  }
  goBack() {
    window.history.go(-1);
  }
  initSF() {
    this.schema = {
      properties: {
        templateName: {
          type: 'string',
          title: '模版名称'
        },
        templateType: {
          title: '模板类型',
          type: 'string',
          enum: [
            { label: '框架合同', value: 'KJ' },
            { label: '明细合同', value: 'MX' },
            { label: '合伙人合同', value: 'HHR' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            change: (tag: any, org: any) => {
              switch (tag) {
                case 'MX':
                  this.Types = [
                    { label: '订单合同', value: '1' },
                    { label: '订单补充协议', value: '2' },
                    { label: '运单合同', value: '3' },
                    { label: '运单补充协议', value: '4' },
                    { label: '委托代收合同', value: '5' },
                    { label: '权力义务转让协议', value: '10' },
                  ];
                  this.sf.getProperty('/contractType')!.schema.enum = this.Types;
                  this.sf.getProperty('/contractType')!.widget.reset(this.Types);
                  this.sf.setValue('/contractType', this.Types);
                  return;
                  break;
                case 'KJ':
                  this.Types = [
                    { label: '网络货物运输服务合同', value: '6' },
                    { label: '运输服务承揽合同', value: '7' }
                  ];
                  this.sf.getProperty('/contractType')!.schema.enum = this.Types;
                  this.sf.getProperty('/contractType')!.widget.reset(this.Types);
                  this.sf.setValue('/contractType', this.Types);
                  return;
                  break;
                case 'HHR':
                  this.Types = [
                    { label: '企业合伙人入驻合同', value: '8' },
                    { label: '个人合伙人入驻合同', value: '9' }
                  ];
                  this.sf.getProperty('/contractType')!.schema.enum = this.Types;
                  this.sf.getProperty('/contractType')!.widget.reset(this.Types);
                  this.sf.setValue('/contractType', this.Types);
                  return;
                  break;
                default:
                  break;
              }
            }
          }
        },
        signingObject: {
          type: 'string',
          title: '承包商对象',
          enum: [
            { label: '货主', value: '1' },
            { label: '司机', value: '2' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        contractType: {
          title: '合同类型',
          type: 'string',
          enum: this.Types,
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        resourceType: {
          title: '货源类型',
          type: 'string',
          default: '',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'goodresource:type' },
            containsAllLable: true,
            visibleIf: {
              templateType: value => value === 'MX'
            }
          } as SFSelectWidgetSchema
        },
        enterpriseInfoId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            visibleIf: {
              templateType: value => value === 'KJ' || value === 'HHR'
            },
            asyncData: () => this.shipperservice.getNetworkFreightForwarder()
          }
        }
      },
      required: ['templateName', 'templateType', 'contractType']
    };
    this.ui = {
      '*': {
        spanLabelFixed: 120,
        grid: { span: 8 }
      }
    };
  }
  initSF2(data?: any) {
    this.schema2 = {
      properties: {
        templateContent: {
          type: 'string',
          title: '',
          ui: {
            widget: 'tinymce',
            loadingTip: 'loading...',
            config: {
              height: 650
            }
          },
          default: data?.agreementContent || ''
        },
       
      },
      required: ['templateContent']
    };
    this.ui2 = {
      '*': {
        grid: { span: 24 }
      },
    };
  }
  initSF3(data?: any) {
    this.schema3 = {
      properties: {
        partyASignX: {
          type: 'string',
          title:'甲方签署位置',
          ui: {
            placeholder: '请输入X',
          }
        },
        partyASignY: {
          type: 'string',
          title:'',
          ui: {
            placeholder: '请输入Y',
          }
        },
        partyBSignX: {
          type: 'string',
          title:'乙方签署位置',
          ui: {
            placeholder: '请输入X',
          }
        },
        partyBSignY: {
          type: 'string',
          title:'',
          ui: {
            placeholder: '请输入Y',
          }
        },
      },
      required: ['partyASignX','partyASignY','partyBSignX','partyBSignY',]
    };
    this.ui3 = {
      '*': {
        spanLabelFixed: 150,
        grid: { span: 24 }
      },
      $partyASignX: {
        grid: { span: 12 }
      },
      $partyASignY: {
        spanLabelFixed: 10,
        grid: { span: 12 }
      },
      $partyBSignX: {
        grid: { span: 12 }
      },
      $partyBSignY: {
        spanLabelFixed: 10,
        grid: { span: 12 }
      },
    };
  }
  initData(url: string) {
    this.service.request(url, { id: this.route.snapshot.params.id }).subscribe(res => {
      if (res) {
        this.detailList = res;
        this.title = this.detailList?.templateName;
        this.sfdata = {
          id: res?.id,
          templateName: res?.templateName,
          templateType: res?.templateType,
          signingObject: res?.signingObject,
          contractType: res?.contractType,
          resourceType: res?.resourceType,
          enterpriseInfoId: res?.enterpriseInfoId,
        };
        this.sfdata2 = {
          templateContent: res?.templateContent,
        };
        this.sfdata3 = {
          partyASignX: res?.partyASignX,
          partyASignY: res?.partyASignY,
          partyBSignX: res?.partyBSignX,
          partyBSignY: res?.partyBSignY,
        };
    
        switch (res.templateType) {
          case 'MX':
            let Types1 = [
              { label: '订单合同', value: '1' },
              { label: '订单补充协议', value: '2' },
              { label: '运单合同', value: '3' },
              { label: '运单补充协议', value: '4' },
              { label: '委托代收合同', value: '5' },
              { label: '权力义务转让协议', value: '10' },
            ];
            setTimeout(() => {
              if (this.sf) {
                this.sf.getProperty('/contractType')!.schema.enum = Types1;
                this.sf.getProperty('/contractType')!.widget.reset(Types1);
                if (res.contractType) {
                  this.sf.setValue('/contractType', res.contractType);
                }
              }
            });

            return;
            break;
          case 'KJ':
            const Types2 = [
              { label: '网络货物运输服务合同', value: '6' },
              { label: '运输服务承揽合同', value: '7' }
            ];
            setTimeout(() => {
              if (this.sf) {
                this.sf.getProperty('/contractType')!.schema.enum = Types2;
                this.sf.getProperty('/contractType')!.widget.reset(Types2);
                if (res.contractType) {
                  this.sf.setValue('/contractType', res.contractType);
                }
              }
            });
            return;
            break;
          case 'HHR':
            const Types3 = [
              { label: '企业合伙人入驻合同', value: '8' },
              { label: '个人合伙人入驻合同', value: '9' }
            ];
            setTimeout(() => {
              if (this.sf) {
                this.sf.getProperty('/contractType')!.schema.enum = Types3;
                this.sf.getProperty('/contractType')!.widget.reset(Types3);
                if (res.contractType) {
                  this.sf.setValue('/contractType', res.contractType);
                }
              }
            });
            return;
            break;
          default:
            break;
        }
      }
    });
  }
  cancel() {
    window.history.go(-1);
  }

  save() {
    console.log(this.sf.value);

    if (
      !this.sf3?.value.partyASignX || 
      !this.sf3?.value.partyASignY || 
      !this.sf3?.value.partyBSignX || 
      !this.sf3?.value.partyBSignY || 
      !this.sf?.value.templateName ||
      !this.sf?.value.templateType ||
      !this.sf2.value.templateContent ||
      !(this.title || this.detailList.templateName)
    ) {
      this.service.msgSrv.error('必填参数为空，请检查再重新保存！');
      return;
    }
    if (this.sf?.value.templateType == 'MX') {
      if (this.sf?.value.contractType == '') {
        this.service.msgSrv.error('必填参数为空，请检查再重新保存！');
        return;
      }
    }
    console.log(this.sf?.value);
    console.log(this.sf2?.value);
    
    const params = {
      ...this.sf?.value,
      partyASignX: this.sf3.value?.partyASignX,
      partyASignY: this.sf3.value?.partyASignY,
      partyBSignX: this.sf3.value?.partyBSignX,
      partyBSignY: this.sf3.value?.partyBSignY,
      templateContent: this.sf2.value?.templateContent,
      templateTitle: this.detailList.templateName || this.title
    };
    console.log(this.sf.value);
    console.log(params);
    
    this.service.request(this.service.$api_save_contractTemplate, params).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('保存成功！');
        this.router.navigate(['/contract-management/template']);
      }
    });
  }
  EditType() {}
  // 下载模板
  downtTemplate() {
    this.service.downloadFile(this.service.$api_downloadTemplatePDF, { id: this.route.snapshot.params.id  });
  }
}
